<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height: 60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="addRole"
              >添加角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="list" border="">
              <el-table-column
                type="index"
                align="center"
                label="序号"
                width="120"
              />
              <el-table-column
                prop="name"
                align="center"
                label="角色名称"
                width="240"
              />
              <el-table-column prop="description" align="center" label="描述" />
              <el-table-column label="操作" align="center">
                <!-- 定义插槽，接收数据 -->
                <template v-slot="{ row }">
                  <el-button size="small" type="success" @click="assignPerm(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="editRole(row.id)">编辑</el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="delRole(row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <el-row
              type="flex"
              justify="center"
              align="middle"
              style="height: 60px"
            >
              <!-- 分页组件 -->
              <el-pagination
                :page-size="page.pagesize"
                :total="page.total"
                layout="prev,pager,next"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form label-width="120px" style="margin-top: 50px">
              <el-form-item label="公司名称">
                <el-input
                  v-model="formData.name"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input
                  v-model="formData.companyAddress"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input
                  v-model="formData.mailbox"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                  v-model="formData.remarks"
                  type="textarea"
                  :rows="3"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <!-- 放置一个弹层 -->
    <el-dialog
      v-bind="$attrs"
      :title="roleForm.id?'编辑角色':'新增角色'"
      :visible="showDialog"
      v-on="$listeners"
      @close="onClose"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="rules"
        size="medium"
        label-width="120px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input
            v-model="roleForm.name"
            placeholder="请输入角色名称"
            clearable
            :style="{ width: '100%' }"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input
            v-model="roleForm.description"
            placeholder="请输入角色描述"
            clearable
            :style="{ width: '100%' }"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <el-row slot="footer" type="flex" justify="center">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </el-row>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog title="分配权限" :visible="showPermDialog" @close="closePerm">
      <!-- 权限是一颗树 -->
      <!-- 将数据绑定到组件上 -->
      <!-- check-strictly 如果为true 那表示父子勾选时  不互相关联 如果为false就互相关联 -->
      <!-- id作为唯一标识 -->
      <el-tree
        ref="treeRef"
        :data="permData"
        :props="{label:'name'}"
        show-checkbox
        check-strictly
        default-expand-all
        :default-checked-keys="selectCheck"
        node-key="id"
      />
      <!-- 确定 取消 -->
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="small" @click="handelPermComfirm">确定</el-button>
          <el-button size="small" @click="closePerm">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleList, getCompanyInfo, deleteRole, getRoleDetail, updateRole, addRole, assignPerm } from '@/api/setting'
import { tranListToTreeData } from '@/utils'
import { getPermissionList } from '@/api/permission'
export default {
  name: 'Setting',
  components: {},
  props: {},
  data() {
    return {
      list: [],
      page: {
        page: 1,
        pagesize: 2,
        total: 0
      },
      formData: {}, // 公司信息

      showDialog: false, // 控制弹层显示
      // 编辑弹层
      roleForm: {
        name: undefined,
        description: undefined,
        id: ''
      },
      rules: {
        name: [{
          required: true,
          message: '请输入角色名称',
          trigger: 'blur'
        }],
        region: []
      },
      showPermDialog: false, // 控制分配权限对话框显示
      permData: [], // 专门用来接收权限数据 树形数据
      selectCheck: [], // 定义一个数组来接收 已经选中的节点
      roleId: null // 用来记录分配角色的id
    }
  },
  async created() {
    this.getRoleList()
    // 调用请求公司信息的接口
    const companyId = this.$store.state.user.userInfo.companyId
    this.formData = await getCompanyInfo(companyId)
  },
  mounted() {},
  methods: {
    // 分配权限
    async assignPerm(id) {
      this.roleId = id
      this.permData = tranListToTreeData(await getPermissionList(), '0')
      const res = await getRoleDetail(id)
      // console.log(res)
      this.selectCheck = res.permIds.map(t => t instanceof Object ? t.id : t)

      this.showPermDialog = true
    },
    closePerm() {
      // 清空选择框
      this.selectCheck = []
      this.showPermDialog = false
    },
    // 确定按钮
    async handelPermComfirm() {
      // 发请求
      await assignPerm({
        id: this.roleId,
        permIds: this.$refs.treeRef.getCheckedKeys()
      })
      this.$message.success('修改权限成功！')
      this.closePerm()
    },
    async getRoleList() {
      const { total, rows } = await getRoleList(this.page)
      this.page.total = total
      this.list = rows
    },
    handleCurrentChange(val) {
      console.log(val)
      this.page.page = val
      this.getRoleList()
    },
    // 删除
    async delRole(id) {
      try {
        // 提示
        await this.$confirm('是否删除？')
        // 点击是
        // 发删除请求
        await deleteRole(id)
        // 提示成功
        this.$message.success('删除成功！')
        // 刷新列表
        this.getRoleList()
      } catch (e) {
        // 点击了 否
        console.log(e)
      }
    },
    // 取消操作
    onClose() {
      this.close()
    },
    // 关闭操作
    close() {
      this.$refs.roleFormRef.resetFields()
      // this.$emit('update:visible', false)
      this.showDialog = false
      this.roleForm = {
        name: '',
        description: '',
        id: ''
      }
    },
    handelConfirm() {
      // 表单校验
      this.$refs['roleFormRef'].validate(async valid => {
        if (!valid) return
        // 校验成功 发请求
        if (this.roleForm.id) {
          // 编辑
          await updateRole(this.roleForm)
        } else {
          // 新增
          await addRole(this.roleForm)
        }
        this.$message.success('操作成功')
        // 刷新
        this.getRoleList()
        this.close()
      })
    },
    // 编辑更新角色
    async editRole(id) {
      this.roleForm = await getRoleDetail(id)
      this.showDialog = true
    },
    // 添加角色
    addRole() {
      this.showDialog = true
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
